package com.demo.test.other;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 匿名内部类导致内存泄露演示代码

 黄色区域解读：
 定义了一个内部类，它是Handler的子类，没有给这个子类定义名字，这个子类重写了Handler的一个方法
 new了一个上述匿名内部类的实例

 需要注意：并不是Handler导致的内存泄露
 **/
public class ActivityLeakA_Handler_fix extends Activity {


    //提示1：This Handler class should be static or leaks might occur (anonymous android.os.Handler)
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };


    //没有提示1
    private Thread mThread = new Thread() {
        @Override
        public void run() {
            super.run();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
            }
        }, 1);
    }


    //采用静态内部类+弱引用（WeakReference）持有外部类实例
    //https://blog.csdn.net/u012982629/article/details/82770282
    private static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity activity) {
            mActivityReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final Activity activity = mActivityReference.get();
            if (activity != null) {
//                activity.xxx ......;
            }
        }
    }


}